package Askgene::Base::Controller::Root;

use warnings;
use strict;

use Askgene::Error;
use aliased 'Reaction::UI::ViewPort';

use base qw/Reaction::UI::Controller::Root/;

sub base : Chained('/') PathPart('') CaptureArgs(0) {
    my ( $self, $c ) = @_;
    my $layout : Stashed = $self->push_viewport( ViewPort, layout => 'layout' );
}

sub static : Chained('/') : PathPart('static') : Args {
    my ( $self, $c, @args ) = @_;
    return if $c->stash->{window}->view->serve_static_file( $c, \@args );
    Askgene::Error->throw( 404 => $c->req->uri );
}

sub default : Private {
    my ( $self, $c ) = @_;
    $c->forward('base');
    Askgene::Error->throw( 404 => $c->req->uri );
}

sub handle_error : Private {
    my ( $self, $c, $error ) = @_;

    $error = {
        status  => 500,
        message => $c->debug ? $error : q{internal server error}
      }
      unless ref $error eq 'HASH';
    my $layout : Stashed;
    $self->pop_viewports_to($layout);
    my $message : Stashed = $error->{message};
    $self->push_viewport( ViewPort, layout => 'error' . $error->{status} );
    $c->res->status( $error->{status} );
    $c->clear_errors;
}

sub end : Private {
    my ( $self, $c ) = @_;
    shift;
    if ( my @errors = @{ $c->error } ) {
        $c->forward( 'handle_error', [ $errors[0] ] );
    }
    eval { $self->SUPER::end(@_) };

    # check if the event flush didn't generate any errors
    if ($@) {
        $c->forward( 'handle_error', [$@] );
        $self->SUPER::end(@_);
    }
}

1;
